import { Box, useCall, useRaf, useSimpleMemo, useToggle } from '@/components';
import { MAIN_RISK_TYPE } from '@/constants/options';
import { defaultShouldUpdate, forkHandler, nextLoop, pathJoin, pathJoinParams } from '@/utils';
import { Button, message, Space, Spin, Tabs } from 'antd';
import React, { useMemo, useRef, useState } from 'react';
import { Route, Switch, useRouteMatch } from 'react-router-dom';
import BasicConfig from './components/BasicConfig';
import BenefitDataConfig from './components/BenefitDataConfig';
import BenefitDescConfig from './components/BenefitDescConfig';
import DefinitionContext, { useDefinitionContext } from './components/Context';
import ShowContentConfig from './components/ShowContentConfig';

const steps = ['', 'benefitData', 'benefitDesc', 'showContent'];

function useStep(parentPath) {
  const step = useRouteMatch(pathJoin(parentPath, '/:current?')).params.current ?? '';
  return steps.indexOf(step);
}

function FixedSpinner({ loading }) {
  const backgroundColor = 'rgba(255, 255, 255, 0.5)';
  const [style, setStyle] = useState({ width: 0, height: 0, backgroundColor });
  const ref = useRef();

  useRaf(() => {
    if (ref.current && loading) {
      const { width, height } = ref.current.getBoundingClientRect();
      if (defaultShouldUpdate(style, { width, height, backgroundColor })) {
        setStyle({ width, height, backgroundColor });
      }
    }
  });

  return (
    <div
      ref={ref}
      style={useMemo(
        () => ({
          position: 'absolute',
          left: 0,
          right: 0,
          top: 0,
          bottom: 0,
          zIndex: 1,
          display: loading ? 'block' : 'none',
        }),
        [loading],
      )}
    >
      <Spin spinning={loading}>
        <div style={style} />
      </Spin>
    </div>
  );
}

function AddPage({ match, location, history }) {
  const step = useStep(match.path);
  const activeKey = `${step + 1}`;
  const [definitionData, setData, loading] = useDefinitionContext();
  const hasShowContent = String(definitionData?.productDefineList?.[0]?.productType) === MAIN_RISK_TYPE;
  const isLastStep = step === 2;
  const nextRoute = `${steps[step + 1] ?? ''}${location.search}`;
  const prevRoute = `${steps[step - 1] || ''}${location.search}`;

  const currentRef = useRef();

  const [pageLoading, toggle] = useToggle(loading);

  const onBack = useCall(() => {
    if (step === 0) {
      history.goBack();
    } else {
      history.replace(pathJoinParams(match.path, prevRoute, location.search));
    }
  });
  const onSave = useCall(
    forkHandler(
      () => {
        if (loading || pageLoading) return false;
        if (!pageLoading) toggle();
        return nextLoop(true);
      },
      () => currentRef.current?.onSave?.() ?? true,
      toggle,
      true,
    ).catch(toggle),
  );

  const onSaveAndNext = useCall(
    forkHandler(
      onSave,
      () => {
        if (isLastStep) {
          history.goBack();
        } else {
          history.replace(pathJoinParams(match.path, nextRoute, location.search));
        }
      },
      true,
    ),
  );

  const onSwitch = useCall(
    forkHandler(
      onSave,
      async (nextKey) => {
        const nextRoute = steps[nextKey - 1];
        if (typeof nextRoute !== 'string') return;
        history.replace(pathJoinParams(match.path, nextRoute, location.search));
      },
      true,
    ),
  );

  return (
    <Box style={{ height: '100%', position: 'relative' }} flex dir='col' scroll ali='stretch'>
      <FixedSpinner loading={loading} />

      <Box shrink={false}>
        <Tabs activeKey={activeKey} onChange={onSwitch}>
          {[
            <Tabs.TabPane tab='基本信息123' key='1' />,
            // <Tabs.TabPane tab='利益演示' key='2' />,
            // <Tabs.TabPane tab='利益责任描述' key='3' />
            definitionData ? <Tabs.TabPane tab='利益演示' key='2' /> : false,
            definitionData ? <Tabs.TabPane tab='利益责任描述' key='3' /> : false,
            // definitionData && hasShowContent ? <Tabs.TabPane tab='阅读文件/文本' key='4' /> : false,
          ].filter(Boolean)}
        </Tabs>
      </Box>

      <DefinitionContext.Provider value={useSimpleMemo({ definitionData, setData })}>
        <Switch>
          <Route path={pathJoin(match.path, '/benefitData')}>
            <BenefitDataConfig ref={currentRef} />
          </Route>
          <Route path={pathJoin(match.path, '/benefitDesc')}>
            <BenefitDescConfig ref={currentRef} />
          </Route>
          <Route path={pathJoin(match.path, '/showContent')}>
            <ShowContentConfig ref={currentRef} />
          </Route>
          <Route>
            <BasicConfig ref={currentRef} />
          </Route>
        </Switch>
      </DefinitionContext.Provider>

      <Box flex jus='center' py={3} className='form-page-btn'>
        <Space size='large'>
          <Button onClick={onBack}>返回</Button>
          <Button onClick={onSaveAndNext} type='primary'>
            {isLastStep ? '完成' : '下一步'}
          </Button>
        </Space>
      </Box>
    </Box>
  );
}

export default AddPage;
